import { ref, computed } from "vue";
import { useChartStore } from "@/store/modules/hmi/chart.store";
import {
  ChartType,
  type ChartDataItem,
  type ChartBaseInfo,
  type VectorDataItem,
  type WaveDataItem,
} from "@/api/hmi/chart.api";

/**
 * 图表数据管理组合式函数
 */
export function useChartData() {
  const chartStore = useChartStore();

  // 本地状态
  const currentType = ref<ChartType | null>(null);
  const currentCpu = ref<number>(1);

  // 计算属性
  const isLoading = computed(() => chartStore.isLoading);
  const error = computed(() => chartStore.error);
  const hasError = computed(() => !!chartStore.error);

  /**
   * 获取图表数据
   * @param type 图表类型
   * @param cpu CPU编号
   */
  const fetchData = async (type: ChartType, cpu: number = 1): Promise<ChartDataItem[]> => {
    try {
      currentType.value = type;
      currentCpu.value = cpu;

      const data = await chartStore.fetchChartData(type, cpu);
      return data;
    } catch (err) {
      console.error("获取图表数据失败:", err);
      throw err;
    }
  };

  /**
   * 获取当前数据
   */
  const getCurrentData = (): ChartDataItem[] => {
    if (!currentType.value) return [];
    return chartStore.getCurrentData(currentType.value);
  };

  /**
   * 获取图表基础信息列表
   */
  const getChartBaseInfoList = (): ChartBaseInfo[] => {
    const data = getCurrentData();
    return data.map((item) => ({
      ID: item.ID,
      Group: item.Group,
      Name: item.Name,
    }));
  };

  /**
   * 根据ID获取单个图表数据
   * @param id 图表ID
   */
  const getChartDataById = (
    id: number
  ): ChartDataItem | WaveDataItem[] | VectorDataItem[] | undefined => {
    const data = getCurrentData();
    if (currentType.value === ChartType.WAVE) {
      return data.filter((item) => item.ID === id) as WaveDataItem[];
    } else if (currentType.value === ChartType.VECTOR) {
      return data.filter((item) => item.ID === id) as VectorDataItem[];
    }
    return data.find((item) => item.ID === id);
  };

  /**
   * 刷新当前数据
   */
  const refreshData = async (): Promise<ChartDataItem[]> => {
    if (!currentType.value) {
      throw new Error("未设置图表类型");
    }
    return await fetchData(currentType.value, currentCpu.value);
  };

  /**
   * 清空数据
   */
  const clearData = () => {
    chartStore.clearData();
    currentType.value = null;
    currentCpu.value = 1;
  };

  /**
   * 重置状态
   */
  const resetState = () => {
    chartStore.resetState();
    currentType.value = null;
    currentCpu.value = 1;
  };

  /**
   * 解析API路径获取图表类型和CPU
   * @param apiPath API路径，如 "hgraph/1"
   */
  const parseApiPath = (apiPath: string): { type: ChartType; cpu: number } => {
    const [apiType, cpuStr] = apiPath.split("/");
    const cpu = parseInt(cpuStr) || 1;

    let type: ChartType;
    switch (apiType) {
      case "hgraph":
        type = ChartType.HARMONIC;
        break;
      case "vplot":
        type = ChartType.VECTOR;
        break;
      case "wplot":
        type = ChartType.WAVE;
        break;
      default:
        throw new Error(`不支持的API类型: ${apiType}`);
    }

    return { type, cpu };
  };

  /**
   * 根据API路径获取数据
   * @param apiPath API路径，如 "hgraph/1"
   */
  const fetchDataByApiPath = async (apiPath: string): Promise<ChartDataItem[]> => {
    const { type, cpu } = parseApiPath(apiPath);
    return await fetchData(type, cpu);
  };

  return {
    // 状态
    currentType,
    currentCpu,
    isLoading,
    error,
    hasError,

    // 方法
    fetchData,
    getCurrentData,
    getChartBaseInfoList,
    getChartDataById,
    refreshData,
    clearData,
    resetState,
    parseApiPath,
    fetchDataByApiPath,
  };
}
